// pages/addMenu/addMenu.js

Page({
 
  data: {
   
    
    objectIndex: 0, //默认显示位置
    selectImgs: undefined,
    uploadImgs: undefined,
    foodnumber:0
  },
 
  onLoad() {
    /* 加载页面时就获取数据库内容的数量 */
    const db = wx.cloud.database()   
    let that = this;
    db.collection("food").count()
    .then(
      (res)=>{
       console.log("获取成功"+res.total)
       that.setData({
         foodnumber: res.total+1
       })
      }
    )
  },
 
  //选择图片
  selectImg() {
    wx.chooseMedia({
      count: 1,
      mediaType:['image'],
      success: (res) => {
        console.log(res)
        this.setData({
          selectImgs: res.tempFiles[0].tempFilePath
        })
      },
      fail:(res)=>
      {
        console.log(res)
      }
    })
  },
  //上传图片到云存储,异步函数，防止图片还没上传，就执行插入云数据库
  uploadImages(foodname) {
    let that = this
    return new Promise(function (resolve, reject) {
      function upload() {
        let date = new Date();
        wx.showLoading({
          title: '上传图片中'
        })
        wx.cloud.uploadFile({
          cloudPath: 'images/'+ foodname + '.png', //给图片命名
          filePath: that.data.selectImgs, //本地图片路径
          success: (res) => {
            //that.data.uploadImgs = res.fileID
            that.setData({
              uploadImgs:res.fileID
            })
            console.log(res.fileID)
            wx.hideLoading({
              success: (res) => {},
            })
           
          },
          fail: (err) => {
            reject('error')
            wx.showToast({
              title: '上传失败，请重新上传',
              type: 'none'
            })
            console.log("failed")
          }
        })
      }
      upload(0)
    })
  },
  //提交表单,保存食品信息到云数据库
  submit(e) {
 
   
    let foodsName = e.detail.value.name //食品名
    let Price = e.detail.value.price //食品价格
    let publisherId = wx.getStorageSync('userInfo')._id //获取发布者id
    let food_location = e.detail.value.food_location //位置信息
    let food_txt = e.detail.value.food_prev;
    let fno = this.data.foodnumber;
    //先上传图片再添加到云数据库
    //点击提交的时候再次校验输入是否有误
    //提交前，利用collection().count()获取food总记录数,总记录值加一即为新的fno（！！！删除时问题很大）
    // 读取count内容被移到onShow方法中

    if (!this.data.isNum ) {
      wx.showToast({
        title: '输入不符，请重新输入',
        icon: 'none'
      })
    } else if(foodsName=='' || Price==null || this.data.selectImgs==null||food_location==null){
      wx.showToast({
        title: '每一项输入信息都不能为空',
        icon: 'none'
      })
    }else{
     // this.uploadImages().then((resolve, reject) => {
        // 自己编写的函数并不是异步的，所以不需要使用上面的方式，直接调用即可
        this.uploadImages(foodsName)
        let imagesUrl = foodsName+'.png' //云存储的图片列表
        wx.showLoading({
          title: '发布中'
        })
        setTimeout(() => {}, 500)
        console.log("插入数据库")
        wx.cloud.database().collection('food').add({
          data: {
            fname: foodsName,
            price: Price *1,
            img: imagesUrl,
            publisher_id: publisherId,
            floc: food_location,
            fno : fno,
            txt: food_txt
          },
          success: (res) => {
            console.log(res)
            wx.hideLoading({
              success: (res) => {
                wx.navigateBack({
                  delta: 1,
                })
              },
            })
          },
          fail:(err)=>{
            console.log(err)
          }
        //})
      })
    }
  },
  reset() {
    //重置图片
    this.setData({
      selectImgs: null,
    })
  },


  //校验价格输入格式
  checkPrice(e) {
    let price = e.detail.value
    let isNum = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
    if (isNum.test(price)) {
      this.setData({
        isNum: true
      })
    } else {
      this.setData({
        isNum: false
      })
      wx.showToast({
        title: '输入价格有误',
        icon: 'none'
      })
    }
  }
})
